<template>
  <div class="main">
    <div class="container">
      <div class="title">
        <span>{{ details.title }}</span>
      </div>
      <div v-if="details.user != undefined" class="user">
        <img :src="details.user.image" alt="" @click="getUserDetails(details.user.uid)" />
        <span @click="getUserDetails(details.user.uid)">{{ details.user.name }}</span>
        <div
          v-if="details.attention != null && details.attention.is_delete == '0'"
        >
          <el-button size="mini" @click="attention(1)">已关注</el-button>
        </div>
        <div v-else>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="attention(0)"
            >关注</el-button
          >
        </div>
      </div>
      <div class="content" v-html="details.content"></div>
      <div class="createtime">{{ details.createtime }}</div>
      <div class="topiccount">
        <!-- 点赞数 -->
        <div
          v-if="details.praise != null && details.praise.status == 0"
          style="display: inline-block"
        >
          <img
            src="../../assets/img/topicicon/like2.png"
            alt=""
            @click="like(1)"
          />
        </div>
        <div v-else style="display: inline-block">
          <img
            src="../../assets/img/topicicon/like1.png"
            alt=""
            @click="like(0)"
          />
        </div>
        <p>{{ details.like_num }}</p>
        <!-- 收藏数 -->
        <div
          v-if="
            details.collect_topic != null &&
            details.collect_topic.is_delete == '0'
          "
          style="display: inline-block"
        >
          <img
            src="../../assets/img/topicicon/collect2.png"
            alt=""
            @click="collect('1')"
          />
        </div>
        <div v-else style="display: inline-block">
          <img
            src="../../assets/img/topicicon/collect1.png"
            alt=""
            @click="collect(id)"
          />
        </div>
        <p>{{ details.collection_num }}</p>
        <template v-if="type == 1">
          <img src="../../assets/img/topicicon/comment1.png" alt="" />
          <p>{{ details.discussion_num }} 条评论</p>
        </template>
        <template v-if="type == 2">
          <img
            @click="dialogVisible = !dialogVisible"
            src="../../assets/img/topicicon/comment1.png"
            alt=""
          />
          <p @click="dialogVisible = !dialogVisible">
            {{ details.discussion_num }} 条评论
          </p>
        </template>
        <span>浏览量 {{ details.browse_num }}</span>
      </div>
    </div>
    <div class="writeReply" v-show="type == 2">
      <span v-if="editShow" @click="editShow = !editShow">
        <i class="el-icon-edit"></i>
        写回答
      </span>
      <div v-else id="replywrite">
        <div style="margin-bottom: 10px;height: 40px">
          <el-button class="submitReply" type="primary" @click="submit"
            >提交</el-button
          >
        </div>
        <!-- 直接隐藏掉就好了，用功能不用样式 -->
        <el-upload
          v-show="false"
          id="quill-upload"
          action="http://localhost:8080/uploadimg"
          name="upload_file"
          multiple
          :limit="3"
          list-type="picture"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-error="uploadError"
          :on-success="handleExceed"
        >
          <!-- <el-button size="small" type="primary"></el-button>
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过500kb
      </div> -->
        </el-upload>
        <el-row v-loading="uillUpdateImg">
          <quillEditor
            ref="myQuillEditor"
            @change="onEditorChange($event)"
            v-model="value"
            :options="editorOption"
          />
        </el-row>
      </div>
    </div>
    <div class="down">
      <discussion v-show="type == 1" :id="id" :type="type"></discussion>
      <!-- <reply-issue v-show="type ==2" :list="replyList"></reply-issue> -->
      <div v-show="type == 2">
        <reply-issue  :list="replyList"></reply-issue>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :hide-on-single-page="true"
            :current-page="query.pageNum"
            :page-size="query.pageSize"
            :total="pageTotal"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="评论" :visible.sync="dialogVisible" width="50%">
      <discussion :id="id" :type="2"></discussion>
    </el-dialog>
  </div>
</template>
<script>
import { findbytid, topicBrowseUp } from "../../api/topic";
import { findDeatils, issueBrowseUp } from "../../api/issue";
import { findReplyByIid,addreply } from "../../api/reply";
import { topiclike_num, topiccollent_num } from "../../api/recommend";
import { attentionUpdate } from "../../api/attention";
import { timeQuantum } from "../../util/timeQuantum";
import Discussion from "../discussion/Discussion";
import ReplyIssue from "../contentshow/ReplyIssue";
// 回答添加
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "TopicDetail",
  components: {
    Discussion,
    ReplyIssue,
    quillEditor
  },
  data() {
    return {
      dialogVisible: false,
      details: {},
      id: 0,
      type: 0,
      query: {
        iid: 0,
        pageNum: 1,
        pageSize: 5,
        uid: localStorage.getItem("uid"),
      },
      pageTotal: 0,
      replyList: {},
      // ******************
      editShow: true,
      uillUpdateImg: false, //根据图片上传状态来确定是否显示loading动画
      value: "",
      editorOption: {
        //符文本编辑器的配置
        placeholder: "",
        theme: "snow",
        modules: {
          toolbar: {
            container: [
              // 工具栏配置, 默认是全部
              ["bold"],
              ["italic"],
              ["underline"],
              ["strike"],
              [{ list: "ordered" }, { list: "bullet" }],
              ["blockquote"],
              ["code-block"],
              ["link"],
              ["image"],
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  // 给个点击触发Element-ui，input框选择图片文件
                  document.querySelector("#quill-upload input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    if (to.params.id == undefined) {
      console.log("未携带tid");
      next(from.path);
    } else {
      next((vm) => {
        vm.type = vm.$route.params.type;
        vm.id = vm.$route.params.id;
        if (vm.type == 2) {
          // 查回答详情
          vm.getReply();
        }
        vm.getData();
        vm.browseUp();
      });
    }
  },
  created() {},
  methods: {
    // 跳转用户详情
    getUserDetails(uid) {
      localStorage.setItem("otherUid", uid)
      this.$router.push("/otheruserpage")
    },
    //修改点赞状态
    like(status) {
      topiclike_num({
        uid: localStorage.getItem("uid"),
        id: this.id,
        status: status,
        type: this.type,
      }).then((res) => {
        if (res.code == 200) {
          this.getData();
        }
      });
    },
    //修改收藏状态
    collect(ttid) {
      topiccollent_num({
        uid: localStorage.getItem("uid"),
        tid: ttid,
        is_delete: "1",
      }).then((res) => {
        if (res.code == 200) {
          this.getData();
        }
      });
    },
    nocollect(ttid) {
      topiccollent_num({
        uid: localStorage.getItem("uid"),
        tid: ttid,
        is_delete: "0",
      }).then((res) => {
        if (res.code == 200) {
          this.getData();
        }
      });
    },
    // 添加浏览量
    browseUp() {
      if (this.type == 1) {
        let data = { tid: this.id };
        topicBrowseUp(data).then((res) => {
          if (res.code != 200) {
            console.log(res.mess);
          }
        });
      } else {
        let data = { iid: this.id };
        // 问题浏览量
        issueBrowseUp(data).then((res) => {
          if (res.code != 200) {
            console.log(res.mess);
          }
        });
      }
    },
    // 用户关注
    attention(status) {
      if (this.details.user.uid == localStorage.getItem("uid")) {
        this.$message.info("不能关注自己");
        return;
      }
      let data = {
        uid: localStorage.getItem("uid"),
        beuid: this.details.user.uid,
        is_delete: status,
      };
      attentionUpdate(data).then((res) => {
        console.log(res);
        this.getData();
      });
    },
    // 获取数据
    getData() {
      // 获取话题详情
      if (this.type == 1) {
        findbytid({
          tid: this.id,
          uid: localStorage.getItem("uid"),
        }).then((res) => {
          this.details = res.data;
          this.details.createtime = timeQuantum(this.details.createtime);
        });
      } else {
        // 获取问题详情
        findDeatils({
          iid: this.id,
          uid: localStorage.getItem("uid"),
        }).then((res) => {
          // console.log(res.data);
          this.details = res.data;
          this.details.createtime = timeQuantum(this.details.createtime);
        });
      }
    },
    // 问题的回答
    getReply() {
      this.query.iid = this.id;
      findReplyByIid(this.query).then((res) => {
        if (res.code == 200) {
          // 分页数据
          this.pageTotal = res.data.total;

          let list = res.data.list;
          var d = document.createElement("div");
          for (let index = 0; index < list.length; index++) {
            // 获取话题内容的文本（用来简略展示）
            d.innerHTML = list[index].content;
            let text = d.innerText;
            if (text.length > 80) {
              list[index].text = text.slice(0, 80) + "...";
            } else {
              list[index].text = text.slice(0, 40) + "...";
            }
            // 统一id
            list[index].id = list[index].rid;
            // 内容展示
            list[index].tag = false;
            // 评论展示
            list[index].disShow = true;

            // 修改时间的展示方式
            list[index].createtime = timeQuantum(list[index].createtime);
          }
          this.replyList = list;
        }
      });
    },
    // 话题的标签

    // ********************** 回答*****************
    replyWrite() {},
    submit() {
      var that = this;
      var data = {
        iid: this.id,
        title: this.details.title,
        content: this.value,
        uid: localStorage.getItem("uid"),
      };
      console.log(data);
      // 判断内容长度
      var d = document.createElement("div");
      d.innerHTML = data.content;
      let text = d.innerText;
      if (text.length == 0) {
        this.$message.info("内容不能为空");
        return;
      }

      addreply(data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          that.$message.success(res.mess);
          this.value = ""
          this.editShow = true
          this.getReply()
        } else {
          that.$message.error(res.mess);
        }
      });
    },

    // **************************************************************************************
    onEditorChange({ quill, html, text }) {
      //富文本编辑器内容发生改变的时候
      this.value = html;
      // this.$emit("textChange", html); //将富文本编辑器输入的文本发送给父组件，父组件涉及提交添加或者更改
    },
    beforeUpload() {
      //上传图片之前开启loading
      this.uillUpdateImg = true;
    },
    uploadError() {
      //图片上传失败,关闭loading
      this.uillUpdateImg = false;
      this.$message.error("图片插入失败");
    },
    handleExceed(response, file, fileList) {
      //图片添加成功
      let quill = this.$refs.myQuillEditor.quill;
      if (response.code === 200) {
        let length = quill.getSelection().index;
        // 插入图片 response.data.url为服务器返回的图片地址
        quill.insertEmbed(length, "image", response.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      this.fileList = fileList;
      this.uillUpdateImg = false;
    },
    // 分页
    handlePageChange(val) {
      this.$set(this.query, "pageNum", val);
      this.getMyTopic();
    },
  }
};
</script>
<style scoped>
.main {
  width: 50%;
  margin: 0 auto;
  /* background-color: #ffffff; */
  /* min-height: 800px; */
}
/* UP */
.container {
  background-color: #ffffff;
  padding: 10px 20px;
  /* border: 1px solid black; */
  color: black;
}
.title {
  font-size: 25px;
  font-weight: bold;
  margin: 10px 0px 20px 10px;
}
.title > span {
  line-height: 35px;
}
.user {
  /* border: 1px solid red; */
  position: relative;
  margin-bottom: 15px;
}
.user > img {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  vertical-align: middle;
}
.user > span {
  margin-left: 10px;
  font-size: 20px;
  color: black;
  vertical-align: middle;
}
.user > div {
  display: inline-block;
  position: absolute;
  right: 0;
}
.content {
  padding: 0px 20px;
  /* border: 1px solid black; */
}
.content >>> p {
  line-height: 30px;
}
.content >>> img {
  display: block;
  width: 60%;
  margin: 0 auto;
}
.content >>> .ql-syntax {
  background-color: #23241f;
  color: #eaeae4;
  /* white-space: nowrap; */
  overflow-y: hidden;
  overflow-x: scroll;
  width: 100%;
}
.createtime {
  padding: 20px 0px 0px 0px;
  color: #8a8a8a;
  font-size: 13px;
}

.topiccount {
  margin: 10px 0px 0px 0px;
  font-size: 16px;
  /* text-align: center; */
}
.topiccount img {
  width: 22px;
  height: 22px;
  vertical-align: middle;
}
.topiccount p {
  display: inline-block;
  margin: 0px 50px 0px 8px;
  vertical-align: middle;
}
.topiccount span {
  font-size: 13px;
  color: #747d8c;
}
/* END UP */

/* 写回答 */
.writeReply {
  margin: 10px 0px;
  background-color: #fff;
  text-align: center;
}
.writeReply > span {
  font-size: 18px;
  line-height: 60px;
}
.writeReply > span:hover {
  color: #409eff;
}
#replywrite {
  position: relative;
}
#replywrite > div {
  background-color: #ffffff;
}
/* .write >>> img {
  width: 200px;
  height: 200px;
} */
#replywrite >>> .ql-editor {
  min-height: 200px;
  color: black;
}
.submitReply {
  position: absolute;
  right: 5px;
  top: 5px;
}


/* 评论 或 回答详情 */
.down {
  /* background-color: #ffffff; */
  margin-top: 8px;
}
/* 分页 */
.pagination {
  margin: 0px auto;
  padding: 20px 0px;
  text-align: center;
  background-color: #fff;
}
</style>